<?php
	//身份验证应用程序的主体部分
	session_start();

	if (isset($_POST['userid']) && isset($_POST['password'])) {
		$userid = $_POST['userid'];
		$password = $_POST['password'];
	}

	$db = new mysqli('localhost', 'webauth', 'webauth', 'auth');

	if (mysqli_connect_errno()) {
		echo "Connection to database failed:".mysqli_connect_error();
		exit();
	}

	$query = "select * from authorized_users" ."where name = '$userid'" ."password = sha1($password)";

	$result = $db->query($query);

	if ($result->num_rows) {
		$_SESSION['valid_user'] = $userid;
	}
	$db->close();
?>

<html>
<body>
	<h1>Home page!</h1>
<?php

	if (isset($_SESSION['valid_user'])) {
		echo 'Your are logged in as:'.$_SESSION['valid_user'].'<br />';
		echo '<a href="logout.php">Log out</a><br />';
	} else {
		if (isset($userid)) {
		//if they have tried and failed to log in.
		echo "Could not log you in.<br />";
		}
		else {
		//they have not tried to log in yet or have logoed out
		echo "Your are not logged in.<br />";
		}	

		//provide form to log in
		echo '<form method="post" action="authmain.php">';
		echo "<table>";
		echo "<tr><td>UserId:</td>";
		echo '<td><input type="text" name="userid"></td></tr>';
		echo "<tr><td>Password:</td>";
		echo '<td><input type="password" name="password"></td></tr>';
		echo '<tr><td colspan="2" align="center">';
		echo '<input type="submit" name="submit" value="Login"></td></tr>';
		echo "</table></form>";
	}
?>

	<br />
	<a href="members_only.php">Members section</a>
</body>
</html>